package edu.suda.basic.security;

import java.io.*;
import java.security.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Digester
{
	public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String getHash(String fileName, String hashType)
			throws Exception
	{
		InputStream fis;
		fis = new FileInputStream(fileName);
		byte[] buffer = new byte[1024];
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		int numRead = 0;
		while ((numRead = fis.read(buffer)) > 0)
		{
			md5.update(buffer, 0, numRead);
		}
		fis.close();
		return toHexString(md5.digest());
	}

	public static String toHexString(byte[] b)
	{
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++)
		{
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	public static Map<String, String> getMessageDigest(String filename,
			List<String> options) throws Exception
	{
		Map<String, String> result = new HashMap<String, String>();
		for (String digestType : options)
		{
			result.put(digestType, getHash(filename, digestType));
		}
		return result;
	}

	public static String getMD5(String filename) throws Exception
	{
		return getHash(filename, "MD5");
	}

	public static String getSHA1(String filename) throws Exception
	{

		return getHash(filename, "SHA1");
	}

	public static String getSHA256(String filename) throws Exception
	{

		return getHash(filename, "SHA-256");
	}

	public static String getSHA384(String filename) throws Exception
	{
		return getHash(filename, "SHA-384");
	}

	public static String getSHA512(String filename) throws Exception
	{
		return getHash(filename, "SHA-512");
	}

}